<?php

namespace support\strategy\sms\impl;

use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use support\Log;
use support\spark\exception\ApiException;
use support\spark\exception\BusinessException;
use support\strategy\sms\SmsInterface;
use Hhink\WebmanSms\Sms;
use Overtrue\EasySms\EasySms;
use think\Validate;

class AliSmsImpl implements SmsInterface
{


    public function send($param)
    {
        try {
            if (!$param["accessKeyId"] || !$param["accessKeySecret"] || !$param["signName"]) {
                throw  new  BusinessException('未配置短信');
            }
            $config = config('plugin.hhink.webman-sms.app');
            $config['gateways']['aliyun']['access_key_id'] = $param["accessKeyId"];
            $config['gateways']['aliyun']['access_key_secret'] = $param["accessKeySecret"];
            $config['gateways']['aliyun']['sign_name'] = $param["signName"];
            $sms = new EasySms($config);
            $sms->send($param['phone'], [
                'content' => "您的登录验证码: {$param['code']}",
                'template' => $param['templateCode'],
                'data' => [
                    'code' => json_decode($param['code'], true)['code']
                ],
            ], ['aliyun']);
        } catch (NoGatewayAvailableException $error) {
            Log::error("发送阿里云短信失败：" . $error->getException('aliyun'));
            throw new ApiException('发送失败', -1);
        } catch (\Throwable $e) {
            Log::error("发送短信失败：" . $e->getMessage());
            throw new ApiException($e->getMessage(), -1);
        }
        return true;
    }
}
